import { DECREMENTGOODS, INCREMENTGOODS, REMOVEGOODS } from "../constant";

let initCart = []

if(localStorage.getItem("cart")){
    initCart = JSON.parse(localStorage.getItem("cart"))
}

export default function cartReducer(preState = initCart, action) {

    const { type, data } = action
    switch (type) {
        case INCREMENTGOODS:
            let isHas = false
            // 购物车存在的
            preState.map((item,index) => {
                if(item.id === data.goods.id){
                    item.count = item.count + data.count
                    isHas = true
                }
            })

            if(!isHas){
                data.goods.count = data.count
                return [data.goods,...preState]
            }
            preState = Object.assign([],preState)

            return preState
        case DECREMENTGOODS:
            preState.map((item) => {
                if(item.id === data){
                    item.count = item.count - 1
                }
            })
            preState = Object.assign([],preState)
            return preState
        case REMOVEGOODS:
            let arr = preState.filter(item => item.id !== data)
            return arr
        default:
            return preState
    }
}